package com.attendance.controller.api;

import com.alibaba.fastjson2.JSON;
import com.attendance.entity.*;
import com.attendance.service.ReportService;
import com.attendance.service.impl.TeamServiceImpl;
import com.attendance.service.impl.UserServiceImpl;
import com.attendance.utils.GenerateEmailContent;
import com.attendance.utils.ResponseInfo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/api/team")
public class TeamController {

    @Resource
    TeamServiceImpl service;

    @Resource
    ReportService reportService;

    @Resource
    public GenerateEmailContent generateEmailContent;

    @PostMapping("/add")
    public String addTeam(@Param("team_name") String team_name, @Param("email") String email, @Param("emoji") String emoji) {
        Integer id = service.selectUserIdByEmail(email);
        HashMap<Object, Object> map = new HashMap<>();
        if (id != null && id != 0) {
            List<Team> teams = service.selectTeamByUserID(id);
            if (!(teams.size() > 0)) {
                service.insert(new Team(null, team_name, id, Integer.parseInt(emoji), false));
                map.put("user_id", id);
                return JSON.toJSONString(ResponseInfo.success(map, "创建成功 ✅"));
            }
            return JSON.toJSONString(ResponseInfo.fail("最多持有一个团队", 500));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("服务器错误 ❌"));
        }
    }

    @GetMapping("/get")
    public String getTeam(@Param("email") String email) {
        Integer id = service.selectUserIdByEmail(email);
        HashMap<Object, Object> map = new HashMap<>();
        if (id != null && id != 0) {
            Team team = service.selectTeamOneByUserId(id);
            map.put("team", team);
            return JSON.toJSONString(ResponseInfo.success(map, "获取成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.success(map, "服务器错误 ❌"));
        }
    }

    @GetMapping("/page")
    public String getPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize
    ) {
        HashMap<Object, Object> map = new HashMap<>();
        IPage<Report> reportIPage = reportService.selectPage(new Page<>(pageNum, pageSize));
        map.put("report", reportIPage);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        return JSON.toJSONString(ResponseInfo.success(map, "获取成功 ✅"));
    }

    @GetMapping("/report")
    public String getReport(@Param("team_id") Integer team_id) {
        HashMap<Object, Object> map = new HashMap<>();
        List<Report> reports = reportService.selectAllByTeamId(team_id);
        map.put("report", reports);
        return JSON.toJSONString(ResponseInfo.success(map, "获取成功 ✅"));
    }

    @PostMapping("/plus")
    public String addReport(@RequestBody Report report) {
        int insert = reportService.insert(report);
        HashMap<Object, Object> map = new HashMap<>();
        if (insert == 1) {
            return JSON.toJSONString(ResponseInfo.success("添加成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("添加失败 ❌"));
        }
    }

    @GetMapping("/leave")
    public String getLeaveTeam(@Param("email") String email) {
        Integer id = service.selectUserIdByEmail(email);
        HashMap<Object, Object> map = new HashMap<>();
        if (id != null && id != 0) {
            List<Team> teams = service.selectTeamByUserIDLeave(id);
            map.put("teams", teams);
            return JSON.toJSONString(ResponseInfo.success(map, "获取成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.success(map, "服务器错误 ❌"));
        }
    }

    @PostMapping("/delete")
    public String deleteReportById(@Param("id") Integer id) {
        int i = reportService.deleteById(id);
        if (i == 1) {
            return JSON.toJSONString(ResponseInfo.success("删除成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("服务器错误 ❌"));
        }
    }

    @PostMapping("/update")
    public String updateReport(@RequestBody Report report) {
        int i = reportService.updateById(report);
        if (i == 1) {
            return JSON.toJSONString(ResponseInfo.success("修改成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("服务器错误 ❌"));
        }
    }

    @GetMapping("/cpxm")
    public String getCpxm() {
        List<Cpxm> cpxms = service.selectCPXM();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("data", cpxms);
        return JSON.toJSONString(ResponseInfo.success(map, "获取成功 ✅"));
    }

    @GetMapping("/cpxh")
    public String getCpxh() {
        List<Cpxh> cpxhs = service.selectCPXH();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("data", cpxhs);
        return JSON.toJSONString(ResponseInfo.success(map, "获取成功 ✅"));
    }

    @GetMapping("/cp")
    public String getCp(@Param("cpxm_id") Integer cpxm_id) {
        List<CpDTO> cpxm = service.selectByGroup(cpxm_id);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("data", cpxm);
        return JSON.toJSONString(ResponseInfo.success(map, "获取成功 ✅"));
    }

    @PostMapping("/cpxmplus")
    public String addCpxm(@RequestBody Cpxm cpxm) {
        int i = service.insertCpxm(cpxm);
        if (i > 0) {
            return JSON.toJSONString(ResponseInfo.success(null, "添加成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("添加失败 ❌", 500));
        }
    }

    @PostMapping("/cpxhplus")
    public String addCpxh(@RequestBody Cpxh cpxh) {
        int i = service.insertCpxh(cpxh);
        if (i > 0) {
            Cpxh detail = service.selectByKeyAndLabel(cpxh);
            if (detail != null) {
                Integer xhId = detail.getId();
                Integer xmid = cpxh.getId();
                i = service.insertCp(new CpxmCpxh(null, xmid, xhId));
                if (i > 0) {
                    HashMap<Object, Object> map = new HashMap<>();
                    List<CpDTO> cpDTOS = service.selectByGroup(xmid);
                    map.put("data", cpDTOS);
                    return JSON.toJSONString(ResponseInfo.success(map, "添加成功 ✅"));
                }
            }
        }
        return JSON.toJSONString(ResponseInfo.fail("添加失败 ❌", 500));
    }

    @GetMapping("/member")
    public String getTeamMember(@Param("team_id") Integer team_id) {
        List<TeamMemberDTO> teamMemberDTO = service.selectTeamMemberById(team_id);
        if (teamMemberDTO.size() > 0) {
            return JSON.toJSONString(ResponseInfo.success(teamMemberDTO, "获取成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("获取失败 ❌", 500));
        }
    }

    @PostMapping("/dcpxh")
    public String deleteCpxh(@Param("id") Integer id) {
        int i = service.deleteCpxh(id);
        if (i > 0) {
            service.deleteCpxmCpxh(id);
            return JSON.toJSONString(ResponseInfo.success(null, "删除成功 ✅"));
        }
        return JSON.toJSONString(ResponseInfo.fail("删除失败 ❌", 500));
    }

    @PostMapping("/upcpxh")
    public String updateCpxh(@RequestBody Cpxh cpxh) {
        int i = service.updateCpxh(cpxh);
        if (i > 0) {
            return JSON.toJSONString(ResponseInfo.success(null, "修改成功 ✅"));
        }
        return JSON.toJSONString(ResponseInfo.fail("修改失败 ❌", 500));
    }

    @PostMapping("/upcpxm")
    public String updateCpxm(@RequestBody Cpxm cpxm) {
        int i = service.updateCpxm(cpxm);
        if (i > 0) {
            return JSON.toJSONString(ResponseInfo.success(null, "修改成功 ✅"));
        }
        return JSON.toJSONString(ResponseInfo.fail("修改失败 ❌", 500));
    }

    @PostMapping("/dcpxm")
    public String deleteCpxm(@Param("id") Integer id) {
        int i = service.deleteCpxm(id);
        if (i > 0) {
            service.deleteCpxhCpxm(id);
            return JSON.toJSONString(ResponseInfo.success(null, "删除成功 ✅"));
        }
        return JSON.toJSONString(ResponseInfo.fail("删除失败 ❌", 500));
    }


    @PostMapping("/upname")
    public String updateUserName(@RequestBody TeamMemberDTO teamMemberDTO) {
        int i = service.updateUserName(teamMemberDTO);
        if (i > 0) {
            return JSON.toJSONString(ResponseInfo.success(null, "修改成功 ✅"));
        }
        return JSON.toJSONString(ResponseInfo.fail("修改失败 ❌", 500));
    }

    @PostMapping("/dteamuser")
    public String deleteTeamUser(@Param("id") Integer id){
        int i = service.deleteTeamUser(id);
        if (i > 0) {
            return JSON.toJSONString(ResponseInfo.success(null, "删除成功 ✅"));
        }
        return JSON.toJSONString(ResponseInfo.fail("删除失败 ❌", 500));
    }

    @PostMapping("/search")
    public String searchUser(@Param("email") String email) {
        List<User> users = service.searchUser(email);
        if (users.size() > 0) {
            return JSON.toJSONString(ResponseInfo.success(users, "搜索成功 ✅"));
        }
        return JSON.toJSONString(ResponseInfo.fail("搜索失败 ❌", 500));
    }

    @Resource
    UserServiceImpl userService;

    @PostMapping("/invite")
    public String inviteToJoin(@RequestBody TeamUser teamUser) {
        Team team = service.selectByTeamId(teamUser.getT_id());
        User user = userService.selectOneById(teamUser.getU_id());
        String toEmail = user.getEmail();
        teamUser.setName(team.getTeam_name());
        Boolean result = generateEmailContent.SendInviteTeamEmail(teamUser, toEmail);
        if (result) {
            return JSON.toJSONString(ResponseInfo.success(null, "发送成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("发送失败 ❌", 500));
        }
    }

    @PostMapping("/agree")
    public void agreeToJoin(@Param("u_id") Integer u_id, @Param("t_id") Integer t_id) {
        service.addTeamUser(new TeamUser(u_id, t_id, null, null, null));
    }

    @PostMapping("/agreea")
    public void agreeToApply(@Param("tId") Integer tId, @Param("uId") Integer uId) {
        service.insertTeamUser(new TeamUser(uId,tId,null,null,null));
    }

    @PostMapping("/apply")
    public String applyToTeam(@Param("userId") Integer userId, @Param("teamId") Integer teamId) {
        User user = userService.selectOneById(userId);
        Boolean result = generateEmailContent.SendApplyTeamEmail(teamId, userId, user);
        if (result) {
            return JSON.toJSONString(ResponseInfo.success(null, "发送成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("发送失败 ❌", 500));
        }
    }

    @Value("${file.upload-dir}")
    private String uploadLocation;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadHistoryExcel(@RequestParam("file") MultipartFile multipartFile, @RequestParam("id") Integer id) {
        if (multipartFile.isEmpty()) {
            return ResponseEntity.badRequest().body("文件为空");
        }
        try {
            LocalDate currentDate = LocalDate.now();
            String fileName = id + "/" + currentDate + ".xlsx";
            Path filePath = Paths.get(uploadLocation, fileName);
            Files.createDirectories(filePath.getParent());
            Files.write(filePath, multipartFile.getBytes());
            String fileUrl = "/static/" + fileName;
            History history = service.selectHistoryByFileName(currentDate.toString());
            if (history == null) {
                service.insertHistory(new History(null, currentDate.toString(), fileUrl, id));
            }
            return ResponseEntity.ok(fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body("文件上传失败");
        }
    }

    @GetMapping("/history")
    public String agreeToJoin(@Param("id") Integer id) {
        List<History> histories = service.selectHistoryByTeamId(id);
        if (histories.size() > 0) {
            return JSON.toJSONString(ResponseInfo.success(histories, "获取成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("获取失败 ❌", 500));
        }
    }

    @GetMapping("/teams")
    public String agreeToJoin(@Param("name") String name) {
        System.out.println(name);
        List<Team> teams = service.searchTeam(name);
        if (teams.size() > 0) {
            return JSON.toJSONString(ResponseInfo.success(teams, "获取成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("获取失败 ❌", 500));
        }
    }

    @GetMapping("/join")
    public String joinTeam(@Param("uid") Integer uid) {
        List<Team> teams = service.selectJoinTeam(uid);
        if (teams.size() > 0) {
            return JSON.toJSONString(ResponseInfo.success(teams, "获取成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("获取失败 ❌", 500));
        }
    }

    @GetMapping("/teamuser")
    public String getTeamUser(@Param("uid") Integer uid) {
        TeamUser teamUser = service.selectTeamUser(uid);
        if (teamUser != null) {
            return JSON.toJSONString(ResponseInfo.success(teamUser, "获取成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("获取失败 ❌", 500));
        }
    }

    @GetMapping("/reportd")
    public String getReportById(@Param("id") Integer id) {
        Report report = reportService.selectById(id);
        if (report != null) {
            return JSON.toJSONString(ResponseInfo.success(report, "获取成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("获取失败 ❌", 500));
        }
    }

    @PostMapping("/upxh")
    public String getReportById(@RequestBody Report report) {
        int i = reportService.updateById(report);
        if (i > 0) {
            return JSON.toJSONString(ResponseInfo.success(null, "提交成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("提交失败 ❌", 500));
        }
    }

    @GetMapping("/userl")
    public String getUserList(@Param("tId") Integer tId){
        List<TeamUserListDTO> teamUserListDTOS = service.selectUserListByTeam(tId);
        if (teamUserListDTOS.size() > 0) {
            return JSON.toJSONString(ResponseInfo.success(teamUserListDTOS, "获取成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("获取失败 ❌", 500));
        }
    }

    @PostMapping("/uprrid")
    public String updateReportRID(@Param("rId") Integer rId, @Param("uId") Integer uId){
        int i = service.updateTutByIdRID(new TutDTO(uId, rId));
        if (i > 0) {
            return JSON.toJSONString(ResponseInfo.success(null, "绑定成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("绑定失败 ❌", 500));
        }
    }

}
